//! 配置服务器与广播功能集成示例
//! 
//! 展示如何在配置服务器中启用和使用配置广播功能

#[cfg(feature = "server")]
#[cfg(feature = "broadcast")]
pub mod config_server_broadcast_example {
    use std::sync::Arc;
    use std::net::SocketAddr;
    
    use crate::server::*;
    use crate::broadcast::*;
    use crate::bus_broadcast::*;
    use crate::core::*;
    
    /// 配置服务器广播集成示例
    pub struct ConfigServerWithBroadcast {
        server: ConfigurationServer,
        broadcast_manager: Arc<AbstractConfigBroadcastManager>,
    }
    
    impl ConfigServerWithBroadcast {
        /// 创建带有配置广播功能的配置服务器
        pub async fn new(
            bind_address: SocketAddr,
            storage: Arc<dyn ConfigurationStorage>,
            message_bus: Arc<dyn ConfigMessageBus>,
            service_name: String,
        ) -> ServerResult<Self> {
            // 创建配置广播管理器
            let broadcast_manager = Arc::new(AbstractConfigBroadcastManager::new(
                message_bus,
                service_name.clone(),
                Some("config.broadcast".to_string()),
            ));
            
            // 创建配置服务并集成广播管理器
            let service = Arc::new(
                ConfigurationService::new(storage)
                    .with_broadcast_manager(broadcast_manager.clone())
            );
            
            // 创建服务器配置
            let mut server_config = ConfigurationServerConfig::default();
            server_config.bind_address = bind_address;
            server_config.server_name = format!("{} with Broadcast", service_name);
            
            // 创建配置服务器
            let server = ConfigurationServer::new(server_config, service);
            
            Ok(Self {
                server,
                broadcast_manager,
            })
        }
        
        /// 启动配置服务器和广播管理器
        pub async fn start(&mut self) -> ServerResult<()> {
            // 启动配置广播管理器
            if let Err(e) = self.broadcast_manager.start().await {
                return Err(ConfigurationServerError::ServerError(
                    format!("启动配置广播管理器失败: {}", e)
                ));
            }
            
            // 启动配置服务器
            self.server.start().await?;
            
            tracing::info!("🚀 配置服务器和广播功能已启动");
            Ok(())
        }
        
        /// 停止配置服务器和广播管理器
        pub async fn stop(&mut self) -> ServerResult<()> {
            // 停止配置服务器
            self.server.stop().await?;
            
            // 停止配置广播管理器
            if let Err(e) = self.broadcast_manager.stop().await {
                tracing::warn!("停止配置广播管理器失败: {}", e);
            }
            
            tracing::info!("🛑 配置服务器和广播功能已停止");
            Ok(())
        }
        
        /// 注册配置变更监听器
        pub async fn register_config_listener(
            &self,
            listener: Box<dyn ConfigBroadcastListener>,
        ) {
            self.broadcast_manager.register_listener(listener).await;
        }
        
        /// 获取集群状态
        pub async fn get_cluster_state(&self) -> std::collections::HashMap<String, ServiceState> {
            self.broadcast_manager.get_cluster_state().await
        }
        
        /// 获取广播统计信息
        pub async fn get_broadcast_stats(&self) -> BroadcastStats {
            self.broadcast_manager.get_broadcast_stats().await
        }
        
        /// 手动广播服务重启请求
        pub async fn broadcast_service_restart(
            &self,
            application: &str,
            target_services: Option<Vec<String>>,
            user: Option<&str>,
        ) -> Result<(), crate::error::ConfigError> {
            self.broadcast_manager
                .broadcast_service_restart(application, target_services, user)
                .await
        }
    }
    
    /// 示例配置变更监听器
    pub struct ExampleConfigListener {
        name: String,
        interested_apps: Vec<String>,
    }
    
    impl ExampleConfigListener {
        pub fn new(name: String, interested_apps: Vec<String>) -> Self {
            Self {
                name,
                interested_apps,
            }
        }
    }
    
    #[async_trait::async_trait]
    impl ConfigBroadcastListener for ExampleConfigListener {
        async fn on_config_change(&self, event: &ConfigBroadcastEvent) -> crate::error::ConfigResult<()> {
            match event.event_type {
                ConfigBroadcastEventType::ConfigUpdate => {
                    tracing::info!(
                        "🔄 [{}] 收到配置更新事件: {} -> {} ({})",
                        self.name,
                        event.application,
                        event.profile,
                        event.id
                    );
                    
                    // 这里可以实现具体的配置更新逻辑
                    // 例如：重新加载配置、重启组件等
                }
                ConfigBroadcastEventType::ConfigDelete => {
                    tracing::info!(
                        "🗑️ [{}] 收到配置删除事件: {} -> {} ({})",
                        self.name,
                        event.application,
                        event.profile,
                        event.id
                    );
                }
                ConfigBroadcastEventType::ConfigRefresh => {
                    tracing::info!(
                        "🔄 [{}] 收到配置刷新事件: {} -> {} ({})",
                        self.name,
                        event.application,
                        event.profile,
                        event.id
                    );
                }
                ConfigBroadcastEventType::ServiceRestart => {
                    tracing::info!(
                        "🔄 [{}] 收到服务重启事件: {} ({})",
                        self.name,
                        event.application,
                        event.id
                    );
                    
                    // 这里可以实现服务重启逻辑
                    // 例如：优雅关闭当前服务，触发重启流程等
                }
            }
            
            Ok(())
        }
        
        fn name(&self) -> &str {
            &self.name
        }
        
        fn should_handle(&self, _event: &ConfigBroadcastEvent) -> bool {
            true
        }
        
        fn interested_applications(&self) -> Vec<String> {
            self.interested_apps.clone()
        }
    }
    
    /// 完整的使用示例
    pub async fn run_example() -> Result<(), Box<dyn std::error::Error>> {
        // 初始化日志
        tracing_subscriber::init();
        
        // 创建内存消息总线（实际使用中可以替换为真实的消息总线实现）
        let message_bus = Arc::new(InMemoryConfigMessageBus::new());
        
        // 创建存储（这里需要一个实际的存储实现）
        // let storage = Arc::new(YourStorageImplementation::new());
        
        // 由于我们没有具体的存储实现，这里用伪代码表示
        /*
        let mut server = ConfigServerWithBroadcast::new(
            "127.0.0.1:8888".parse()?,
            storage,
            message_bus,
            "config-server-1".to_string(),
        ).await?;
        
        // 注册配置变更监听器
        let listener = Box::new(ExampleConfigListener::new(
            "main-listener".to_string(),
            vec!["user-service".to_string(), "order-service".to_string()],
        ));
        server.register_config_listener(listener).await;
        
        // 启动服务器
        server.start().await?;
        
        tracing::info!("🎉 配置服务器已启动，支持配置广播功能");
        
        // 模拟运行一段时间
        tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
        
        // 获取集群状态
        let cluster_state = server.get_cluster_state().await;
        tracing::info!("📊 集群状态: {:?}", cluster_state);
        
        // 获取广播统计
        let broadcast_stats = server.get_broadcast_stats().await;
        tracing::info!("📈 广播统计: {:?}", broadcast_stats);
        
        // 停止服务器
        server.stop().await?;
        */
        
        tracing::info!("✅ 示例运行完成");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    #[cfg(feature = "broadcast")]
    async fn test_config_server_broadcast_integration() {
        // 测试配置服务器与广播功能的集成
        let message_bus = Arc::new(InMemoryConfigMessageBus::new());
        
        // 这里应该有具体的存储实现测试
        // 由于依赖具体的存储实现，暂时跳过
        
        // 测试广播管理器创建
        let broadcast_manager = AbstractConfigBroadcastManager::new(
            message_bus,
            "test-config-server".to_string(),
            Some("config.broadcast".to_string()),
        );
        
        // 测试广播统计
        let stats = broadcast_manager.get_broadcast_stats().await;
        assert_eq!(stats.events_sent, 0);
        assert_eq!(stats.events_received, 0);
        assert_eq!(stats.active_listeners, 0);
    }
}